
/*-----------------------------------------------------VIEW MODELS
------------------------------------------------*/
var UploadFileModel = new function () {

    this.DisplayFirstView = ko.observable(true);
    this.classLead = ko.observable(data.LeadCall.LeadStatus);

    this.classLeadDisplay = ko.computed(function () 
    {
        if (this.classLead()) {
            return 'btn btn-leads-on';
        }
        else {
            return 'btn btn-leads-off';
        }
    }, this);
    this.classCall = ko.observable(data.LeadCall.CallStatus);
    this.classCallDisplay = ko.computed(function () {
        if (this.classCall()) {
            return 'btn btn-calls-on';
        }
        else {
            return 'btn btn-calls-off';
        }
    }, this);

};


var HelpModel = new function () 
{
    this.classLead = ko.observable(data.LeadCall.LeadStatus);
    this.classLeadDisplay = ko.computed(function () {
        if (this.classLead()) {
            return 'btn btn-leads-on';
        }
        else {
            return 'btn btn-leads-off';
        }
    }, this);
    this.classCall = ko.observable(data.LeadCall.CallStatus);
    this.classCallDisplay = ko.computed(function () {
        if (this.classCall()) {
            return 'btn btn-calls-on';
        }
        else {
            return 'btn btn-calls-off';
        }
    }, this);
    this.DisplayHelp = ko.observable(false);
    this.GoBackStep1 = function () {
        UploadFileModel.DisplayFirstView(true);
        DeleteUpload();
        HelpModel.DisplayHelp(false);
        MappingModel.DisplaySecondView(false);
        ReviewImportModel.DisplayThirdView(false);


    };



    this.GoToMatch = function () {


        $.fancybox($('#popup-processing-getmapping'), {
            padding: 0,
            closeBtn: false,
            helpers: {
                overlay: {
                    opacity: 0.8,
                    css: { 'background-color': '#11619d' },
                    closeClick: false
                }
            }
        });

        var ManualImportId = $('#StoreManualID').val();

        if (ManualImportId != undefined) {

            var dataPost = { "manualImportID": ManualImportId };

            $.ajax({
                type: "POST",
                url: "/EnhancedManualImport/GetMapping",
                data: dataPost,
                dataType: "json",
                success: function (ModelFields, textStatus, jqXHR) {
                    $.fancybox.close();
                    if ((ModelFields != "") && (ModelFields.Mapping.Columns != null)) {
                        UploadFileModel.DisplayFirstView(false);
                        HelpModel.DisplayHelp(false);

                        MappingModel.AllFieldGroups(ModelFields.Mapping.AllFieldGroups);

                        MappingModel.DisplaySecondView(true);
                        ReviewImportModel.DisplayThirdView(false);
                        // build array with items
                        var items = [];
                        var firstUnmappedColumnName = "";
                        var count = 0;
                        var unmappedCount = 0;
                        //found unmapped column

                        for (var i = 0; i < ModelFields.Mapping.Columns.length; i++) {
                            var item = ModelFields.Mapping.Columns[i];
                            if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
                                firstUnmappedColumnName = item.ColumnName;
                                break;
                            }
                        }

                        for (var i = 0; i < ModelFields.Mapping.Columns.length; i++) {
                            var item = ModelFields.Mapping.Columns[i];
                            var newItem = {
                                ColumnName: item.ColumnName,
                                IsIgnored: item.IsIgnored,
                                PossibleGroups: item.PossibleGroups,
                                PossibleFieldsInOrder: item.PossibleFieldsInOrder,
                                MappedField: item.MappedField,
                                IsActive: item.ColumnName == firstUnmappedColumnName ? true : false
                            };
                            items.push(newItem);
                            if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
                                unmappedCount = unmappedCount + 1;
                            }
                        }
                        MappingModel.MappingColumns(items);
                        MappingModel.TotalMatchedHeaders(ModelFields.Mapping.Columns.length - unmappedCount);
                        MappingModel.TotalHeaders(ModelFields.Mapping.Columns.length);
                        MappingModel.UpdateView();
                    }
                    else {
                        showPopupError();
                    }
                },
                error: function (xhr, status, error) {
                    $.fancybox.close();
                    showCustomError(eval("(" + xhr.responseText + ")"));
                }
            });

        };
    };

};

var MappingModel = new function () {

    this.classLead = ko.observable(data.LeadCall.LeadStatus);
    this.classLeadDisplay = ko.computed(function () {
        if (this.classLead()) {
            return 'btn btn-leads-on';
        }
        else {
            return 'btn btn-leads-off';
        }
    }, this);
    this.classCall = ko.observable(data.LeadCall.CallStatus);
    this.classCallDisplay = ko.computed(function () {
        if (this.classCall()) {
            return 'btn btn-calls-on';
        }
        else {
            return 'btn btn-calls-off';
        }
    }, this);
    this.DisplaySecondView = ko.observable(false);
    this.TotalHeaders = ko.observable(40);
    this.HeaderText = ko.computed(function () {
        if (this.TotalHeaders() > 1) {
            return "headers matched";
        }
        else {
            return "header matched";
        }

    }, this);


    this.TotalMatchedHeaders = ko.observable(17);
    this.ProgressValue = ko.observable('0%');
    this.CheckProgressValue = ko.computed(function () {
        this.ProgressValue((100 * this.TotalMatchedHeaders() / this.TotalHeaders()) + '%');
    }, this);
    this.MappingColumns = ko.observableArray();

    this.AllFieldGroups = ko.observableArray();
    this.DisplayedColumns = ko.observableArray();
    this.DisplayedGroups = ko.observableArray();
    this.CurrentFieldGroups = ko.observableArray();
    this.CurrentFieldsInOrder = ko.observableArray();

    this.ViewType = "All"; //All, Unmatched

    this.SearchFieldText = ko.observable("Search Header Names");

    this.FilterMode = ko.observable("DataType"); // DataType, All
    this.ActiveColumn = null;
    this.LastMappedColumns = "";
    this.Initialized = false;
    this.AllColumnsMapped = ko.observable(false);

    this.EnableSearch = ko.computed(function () {
        if (this.DisplayedGroups().length > 0 || (this.TotalHeaders() - this.TotalMatchedHeaders()) > 0) {

            return true;
        }
        else {

            return false;
        }

    }, this);




    this.UpdateView = function () {
        var unmappedCount = 0;
        this.Initialized = true;
        var firstUnmappedColumnName = "";
        this.DisplayedColumns.removeAll();
        this.DisplayedGroups.removeAll();
        $(".i-matched").remove();
        $(".i-matched1").remove();
        var foundFirstItem = false;

        if (this.ViewType == "All") {
            for (var i = 0; i < this.MappingColumns().length; i++) {
                var item = this.MappingColumns()[i];
                if (item.IsIgnored == false) {
                    if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
                        unmappedCount = unmappedCount + 1;
                    }
                    var newItem = {
                        ColumnName: item.ColumnName,
                        IsIgnored: item.IsIgnored,
                        PossibleGroups: item.PossibleGroups,
                        PossibleFieldsInOrder: item.PossibleFieldsInOrder,
                        MappedField: item.MappedField,
                        IsActive: false
                    };
                    if ((typeof (item.MappedField) == "undefined" || item.MappedField == null)
						&& (!foundFirstItem) && (item.IsIgnored != true)) {

                        firstUnmappedColumnName = item.ColumnName;
                        foundFirstItem = true;
                        newItem.IsActive = true;
                        this.ActiveColumn = newItem;
                    }
                    this.DisplayedColumns.push(newItem);
                }
            }
            if (!foundFirstItem) {
                this.ActiveColumn = null;
                this.AllColumnsMapped(true);
            }
        }
        else {
            for (var i = 0; i < this.MappingColumns().length; i++) {
                var item = this.MappingColumns()[i];
                if (item.IsIgnored == false) {
                    if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
                        unmappedCount = unmappedCount + 1;
                        var newItem = {
                            ColumnName: item.ColumnName,
                            IsIgnored: item.IsIgnored,
                            PossibleGroups: item.PossibleGroups,
                            PossibleFieldsInOrder: item.PossibleFieldsInOrder,
                            MappedField: item.MappedField,
                            IsActive: false
                        };
                        if (!foundFirstItem) {
                            newItem.IsActive = true;
                            firstUnmappedColumnName = item.ColumnName;
                            foundFirstItem = true;
                            newItem.IsActive = true;
                            this.ActiveColumn = newItem;
                        }
                        this.DisplayedColumns.push(newItem);
                    }
                }
            }
            if (!foundFirstItem) {
                this.ActiveColumn = null;
                this.AllColumnsMapped(true);
            }
        }
        if (this.ActiveColumn == null) {
            MappingModel.TotalMatchedHeaders(this.MappingColumns().length - unmappedCount);
            document.getElementById("NextToStep3").setAttribute("class", "btn btn-next-blue right");
            //All fields are mapped, nothing will be showed in the right panel

            return;
        }
        else {
            document.getElementById("NextToStep3").setAttribute("class", "btn btn-next-gray right");
        }
        if ((this.FilterMode() == "DataType") && ((this.SearchFieldText() == "") || (this.SearchFieldText() == "Search Header Names"))) {

            this.CurrentFieldGroups(clone(this.ActiveColumn.PossibleGroups));
            this.CurrentFieldsInOrder(clone(this.ActiveColumn.PossibleFieldsInOrder));
        }
        else {
            this.CurrentFieldGroups(clone(this.AllFieldGroups()));
        }
        MappingModel.TotalMatchedHeaders(this.MappingColumns().length - unmappedCount);
        this.FilterFieldGroups();
        this.DisplayedGroups(this.CurrentFieldGroups());
        if (this.ActiveColumn != "undefined" && this.ActiveColumn != null)
            document.getElementById(this.ActiveColumn.ColumnName).scrollIntoView(true);



    };


    this.FilterFieldGroups = function () {
        if ((this.FilterMode() == "DataType") && ((this.SearchFieldText() == "") || (this.SearchFieldText() == "Search Header Names"))) {
            for (var i = this.CurrentFieldsInOrder().length - 1; i > -1; i--) {
                if (this.CurrentFieldsInOrder()[i].IsUsed == "true") {
                    this.CurrentFieldsInOrder().splice(i, 1);
                }
            }
            if (this.CurrentFieldsInOrder().length > 10) {
                this.CurrentFieldsInOrder().splice(10, this.CurrentFieldsInOrder().length - 10);
            }

            for (var i = this.CurrentFieldGroups().length - 1; i > -1; i--) {
                var groupItem = this.CurrentFieldGroups()[i];
                var groupHasChildren = false;
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var j = groupItem.Fields.length - 1; j > -1; j--) {
                        var fieldItem = groupItem.Fields[j];
                        if (fieldItem.IsUsed == true) {
                            groupItem.Fields.splice(j, 1);
                        }
                        else {
                            var found = false;
                            for (var k = 0; k < this.CurrentFieldsInOrder().length; k++) {
                                var orderedFI = this.CurrentFieldsInOrder()[k];
                                if (fieldItem.FieldId == orderedFI.FieldId) {
                                    found = true;
                                    break;
                                }
                            }
                            if (found == false) {
                                groupItem.Fields.splice(j, 1);
                            }
                        }
                    }
                    if (groupItem.Fields.length > 0) {
                        groupHasChildren = true;
                    }
                }
                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var j = groupItem.Sections.length - 1; j > -1; j--) {
                        var sectionItem = groupItem.Sections[j];
                        for (var k = sectionItem.Fields.length - 1; k > -1; k--) {
                            var fieldItem = sectionItem.Fields[k];
                            if (fieldItem.IsUsed == true) {
                                sectionItem.Fields.splice(k, 1);
                            }
                            else {
                                var found = false;
                                for (var l = 0; l < this.CurrentFieldsInOrder().length; l++) {
                                    var orderedFI = this.CurrentFieldsInOrder()[l];
                                    if (fieldItem.FieldId == orderedFI.FieldId) {
                                        found = true;
                                        break;
                                    }
                                }
                                if (found == false) {
                                    sectionItem.Fields.splice(k, 1);
                                }
                            }
                        }
                        if (sectionItem.Fields.length > 0) {
                            groupHasChildren = true;
                        }
                        else {
                            groupItem.Sections.splice(j, 1);
                        }
                    }
                    if (groupItem.Sections.length == 0) {
                        groupItem.Sections = null;
                    }
                }
                if (groupHasChildren == false) {
                    this.CurrentFieldGroups().splice(i, 1);
                }
            }
        }
        else {
            for (var i = this.CurrentFieldGroups().length - 1; i > -1; i--) {
                var groupItem = this.CurrentFieldGroups()[i];
                var groupHasChildren = false;
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var j = groupItem.Fields.length - 1; j > -1; j--) {
                        var fieldItem = groupItem.Fields[j];
                        if (fieldItem.IsUsed == true) {
                            groupItem.Fields.splice(j, 1);
                        }
                        else {
                            if ((this.SearchFieldText() != "") && (this.SearchFieldText() != "Search Header Names")) {
                                if (fieldItem.FieldName.toLowerCase().indexOf(this.SearchFieldText().toLowerCase()) == -1) {
                                    groupItem.Fields.splice(j, 1);
                                }
                            }
                        }
                    }
                    if (groupItem.Fields.length > 0) {
                        groupHasChildren = true;
                    }
                }
                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var j = groupItem.Sections.length - 1; j > -1; j--) {
                        var sectionItem = groupItem.Sections[j];
                        for (var k = sectionItem.Fields.length - 1; k > -1; k--) {
                            var fieldItem = sectionItem.Fields[k];
                            if (fieldItem.IsUsed == true) {
                                sectionItem.Fields.splice(k, 1);
                            }
                            else {
                                if ((this.SearchFieldText() != "") && (this.SearchFieldText() != "Search Header Names")) {
                                    if (fieldItem.FieldName.toLowerCase().indexOf(this.SearchFieldText().toLowerCase()) == -1) {
                                        sectionItem.Fields.splice(k, 1);
                                    }
                                }
                            }
                        }
                        if (sectionItem.Fields.length > 0) {
                            groupHasChildren = true;
                        }
                        else {
                            groupItem.Sections.splice(j, 1);
                        }
                    }
                    if (groupItem.Sections.length == 0) {
                        groupItem.Sections = null;
                    }
                }
                if (groupHasChildren == false) {
                    this.CurrentFieldGroups().splice(i, 1);
                }
            }
        }
    }


    this.ViewAllFields = function () {
        this.FilterMode("All");
        this.SearchFieldText("");
        this.UpdateView();
        this.SearchFieldText("Search Header Names");

    };


    this.EnterHandler = function (MappingModel, event) {
        if (event.keyCode == 13) {
            this.SearchFieldText($('#searchKeywordstep2').val());
            if ((this.SearchFieldText() != "Search Header Names") || (this.FilterMode() != "DataType")) {
                this.FilterMode("DataType");
                this.UpdateView();
            }
        }
        return true;
    }

    this.SearchFields = function () {
        if ((this.SearchFieldText() != "Search Header Names") || (this.FilterMode() != "DataType")) {
            this.FilterMode("DataType");
            this.UpdateView();
        }
        if (this.SearchFieldText() == "") {
            this.SearchFieldText("Search Header Names");
        }
    };

    this.GoBackHelp = function () {
        UploadFileModel.DisplayFirstView(false);
        HelpModel.DisplayHelp(true);
        MappingModel.DisplaySecondView(false);
        ReviewImportModel.DisplayThirdView(false);
    };

    this.MatchColumn = function (fieldId, fieldName) {
        if ((fieldId == null) || (fieldId == 0)) return;
        if (this.ActiveColumn == null) return;
        // Update the column mappings
        for (var i = 0; i < this.MappingColumns().length; i++) {
            var columnItem = this.MappingColumns()[i];
            // Update the current column
            if (columnItem.ColumnName == this.ActiveColumn.ColumnName) {
                columnItem.MappedField = {
                    FieldId: fieldId,
                    FieldName: fieldName
                };
            }

            // update all possible fields of all columns to mark the dropped field as IsUsed
            var found = false;
            for (var j = 0; j < columnItem.PossibleGroups.length; j++) {
                var groupItem = columnItem.PossibleGroups[j];
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var k = 0; k < groupItem.Fields.length; k++) {
                        var fieldItem = groupItem.Fields[k];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = true;
                            found = true;
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var k = 0; k < groupItem.Sections.length; k++) {
                        var sectionItem = groupItem.Sections[k];
                        for (var h = 0; h < sectionItem.Fields.length; h++) {
                            var fieldItem = sectionItem.Fields[h];
                            if (fieldItem.FieldId == fieldId) {
                                fieldItem.IsUsed = true;
                                found = true;
                                break;
                            }
                        }
                        if (found == true) {
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
            }
            for (var j = 0; j < columnItem.PossibleFieldsInOrder.length; j++) {
                var fieldItem = columnItem.PossibleFieldsInOrder[j];
                if (fieldItem.FieldId == fieldId) {
                    fieldItem.IsUsed = true;
                    break;
                }
            }
        }

        // Update the all fields to mark the dropped field as IsUsed
        var found1 = false;
        for (var j = 0; j < this.AllFieldGroups().length; j++) {
            var groupItem = this.AllFieldGroups()[j];
            if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                for (var k = 0; k < groupItem.Fields.length; k++) {
                    var fieldItem = groupItem.Fields[k];
                    if (fieldItem.FieldId == fieldId) {
                        fieldItem.IsUsed = true;
                        found1 = true;
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
            if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                for (var k = 0; k < groupItem.Sections.length; k++) {
                    var sectionItem = groupItem.Sections[k];
                    for (var h = 0; h < sectionItem.Fields.length; h++) {
                        var fieldItem = sectionItem.Fields[h];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = true;
                            found1 = true;
                            break;
                        }
                    }
                    if (found1 == true) {
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
        }

    };

    this.x_OutColumn = function (data) {
        MappingModel.UnMatchColumn(data.ColumnName, true);
        MappingModel.UpdateView();

    };

    this.UnMatchColumn = function (columnName, ignore) {

        // Update the column mappings
        var fieldId = 0;
        for (var i = 0; i < this.MappingColumns().length; i++) {
            var columnItem = this.MappingColumns()[i];
            // Update the current column
            if (columnItem.ColumnName == columnName) {
                if ((typeof (columnItem.MappedField) != "undefined") && (columnItem.MappedField != null)) {
                    fieldId = columnItem.MappedField.FieldId;
                    columnItem.MappedField = null;
                }
                if (ignore == true) {
                    columnItem.IsIgnored = true;
                }
                else {
                    columnItem.IsIgnored = false;
                }
                break;
            }
        }

        if (fieldId == 0) return;

        for (var i = 0; i < this.MappingColumns().length; i++) {
            var columnItem = this.MappingColumns()[i];

            // update all possible fields of all columns to mark the undropped field as IsUnUsed
            var found = false;
            for (var j = 0; j < columnItem.PossibleGroups.length; j++) {
                var groupItem = columnItem.PossibleGroups[j];
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var k = 0; k < groupItem.Fields.length; k++) {
                        var fieldItem = groupItem.Fields[k];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = false;
                            found = true;
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var k = 0; k < groupItem.Sections.length; k++) {
                        var sectionItem = groupItem.Sections[k];
                        for (var h = 0; h < sectionItem.Fields.length; h++) {
                            var fieldItem = sectionItem.Fields[h];
                            if (fieldItem.FieldId == fieldId) {
                                fieldItem.IsUsed = false;
                                found = true;
                                break;
                            }
                        }
                        if (found == true) {
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
            }
            for (var j = 0; j < columnItem.PossibleFieldsInOrder.length; j++) {
                var fieldItem = columnItem.PossibleFieldsInOrder[j];
                if (fieldItem.FieldId == fieldId) {
                    fieldItem.IsUsed = false;
                    break;
                }
            }

        }

        // Update the all fields to mark the dropped field as IsUnUsed
        var found1 = false;
        for (var j = 0; j < this.AllFieldGroups().length; j++) {
            var groupItem = this.AllFieldGroups()[j];
            if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                for (var k = 0; k < groupItem.Fields.length; k++) {
                    var fieldItem = groupItem.Fields[k];
                    if (fieldItem.FieldId == fieldId) {
                        fieldItem.IsUsed = false;
                        found1 = true;
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
            if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                for (var k = 0; k < groupItem.Sections.length; k++) {
                    var sectionItem = groupItem.Sections[k];
                    for (var h = 0; h < sectionItem.Fields.length; h++) {
                        var fieldItem = sectionItem.Fields[h];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = false;
                            found1 = true;
                            break;
                        }
                    }
                    if (found1 == true) {
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
        }

    };
    this.GoToDataCorrection = function () {
        if (this.AllColumnsMapped() == false) return;
        var ManualImportId = $('#StoreManualID').val();
        var columnSeparator = ";$;";
        var propertySeparator = ";#;";
        var mappingSettings = "";

        for (var i = 0; i < this.MappingColumns().length; i++) {
            var mappingItem = this.MappingColumns()[i];
            if (i == 0) {
                mappingSettings = mappingItem.ColumnName
					+ propertySeparator
					+ mappingItem.IsIgnored
					+ propertySeparator
					+ ((mappingItem.MappedField == null) ? 0 : mappingItem.MappedField.FieldId);
            }
            else {
                mappingSettings = mappingSettings
					+ columnSeparator
					+ mappingItem.ColumnName
					+ propertySeparator
					+ mappingItem.IsIgnored
					+ propertySeparator
					+ ((mappingItem.MappedField == null) ? 0 : mappingItem.MappedField.FieldId);
            }
        }
        init_review_import();
        hscroll_size(); // Comment here

        var dataPost = { "manualImportID": ManualImportId, "MappingSettings": mappingSettings };

        $.ajax({
            type: "POST",
            url: "/EnhancedManualImport/SaveMappingAndGetDataErrors",
            data: dataPost,
            dataType: "json",
            success: function (dataErrors, textStatus, jqXHR) {
                $.fancybox.close();
                $('#DoNotImportLeadswithErrors').removeAttr("jcf-hidden");
                $('#DoNotImportLeadswithErrors').attr("class", "jcf-select");

                if (dataErrors.IsError == true) {
                    showCustomError(dataErrors.ErrorMessage);
                }
                else {
                    //Update IsIgnored in CellModel
                    var _ErrorRows = dataErrors.DataError.ErrorRows;
                    var _ColumnHeaders = dataErrors.DataError.ColumnHeaders;
                    var countErrorRows = _ErrorRows.length;
                    var countColumnHeaders = _ColumnHeaders.length;
                    if (countColumnHeaders > 0) {
                        for (var i = 0; i < countColumnHeaders; i++) {
                            if (countErrorRows > 0) {
                                for (var j = 0; j < countErrorRows; j++) {
                                    if (_ColumnHeaders[i].IsIgnored) {
                                        _ErrorRows[j].Cells[i].IsIgnored = true;
                                    }
                                    _ErrorRows[j].Cells[i].CellID = i + '-' + j;
                                    _ErrorRows[j].Cells[i].IsDone = false;

                                    //set class for cell
                                    if (_ErrorRows[j].Cells[i].IsDone) {
                                        _ErrorRows[j].Cells[i].ClassName = "col1 done";
                                    }
                                    else if (_ErrorRows[j].Cells[i].IsError) {
                                        _ErrorRows[j].Cells[i].ClassName = "col1 error";
                                    }
                                    else {
                                        _ErrorRows[j].Cells[i].ClassName = "col1";
                                    }
                                }
                            }
                        }
                    }
                    if (countErrorRows > 0) {
                        var displayError = false;
                        for (var i = 0; i < _ErrorRows[0].Cells.length; i++) {
                            if (!_ErrorRows[0].Cells[i].IsIgnored) {
                                if ((_ErrorRows[0].Cells[i].IsError == true) || (_ErrorRows[0].Cells[i].Value == "")) {
                                    displayError = true;
                                    break;
                                }
                            }
                        }
                        ReviewImportModel.HasErrorsToDisplay(displayError);
                    }
                    else {
                        ReviewImportModel.HasErrorsToDisplay(false);
                    }

                    UploadFileModel.DisplayFirstView(false);
                    HelpModel.DisplayHelp(false);
                    MappingModel.DisplaySecondView(false);
                    ReviewImportModel.DisplayThirdView(true);
                    hscroll_size(); // Comment here

                    ReviewImportModel.ColumnHeaders(dataErrors.DataError.ColumnHeaders);
                    ReviewImportModel.ErrorRows(_ErrorRows);
                }
            },
            error: function (xhr, status, error) {
                $.fancybox.close();
                showCustomError(eval("(" + xhr.responseText + ")"));
            }
        });
    };
};


function clone(src) {
    function mixin(dest, source, copyFunc) {
        var name, s, i, empty = {};
        for (name in source) {
            // the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
            // inherited from Object.prototype.   For example, if dest has a custom toString() method,
            // don't overwrite it with the toString() method that source inherited from Object.prototype
            s = source[name];
            if (!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))) {
                dest[name] = copyFunc ? copyFunc(s) : s;
            }
        }
        return dest;
    }

    if (!src || typeof src != "object" || Object.prototype.toString.call(src) === "[object Function]") {
        // null, undefined, any non-object, or function
        return src;  // anything
    }
    if (src.nodeType && "cloneNode" in src) {
        // DOM Node
        return src.cloneNode(true); // Node
    }
    if (src instanceof Date) {
        // Date
        return new Date(src.getTime());  // Date
    }
    if (src instanceof RegExp) {
        // RegExp
        return new RegExp(src);   // RegExp
    }
    var r, i, l;
    if (src instanceof Array) {
        // array
        r = [];
        for (i = 0, l = src.length; i < l; ++i) {
            if (i in src) {
                r.push(clone(src[i]));
            }
        }
        // we don't clone functions for performance reasons
        //} else if(d.isFunction(src)) {
        //	// function
        //	r = function(){ return src.apply(this, arguments); };
    } else {
        // generic objects
        r = src.constructor ? new src.constructor() : {};
    }
    return mixin(r, src, clone);



}


var ReviewImportModel = new function () {

    this.classLead = ko.observable(data.LeadCall.LeadStatus);
    this.classLeadDisplay = ko.computed(function () {
        if (this.classLead()) {
            return 'btn btn-leads-on';
        }
        else {
            return 'btn btn-leads-off';
        }
    }, this);
    this.classCall = ko.observable(data.LeadCall.CallStatus);
    this.classCallDisplay = ko.computed(function () {
        if (this.classCall()) {
            return 'btn btn-calls-on';
        }
        else {
            return 'btn btn-calls-off';
        }
    }, this);
    this.titleReviewandImport = ko.observable('We have identified some errors and missing data in your file.');
    this.DisplayThirdView = ko.observable(false);
    this.ColumnHeaders = ko.observableArray([]);
    this.DisplayColumnHeaders = ko.observableArray([]);
    this.ErrorRows = ko.observableArray([]);
    this.DisplayErrorRows = ko.observableArray([]);
    this.HasErrorsToDisplay = ko.observable();
    this.ActiveMoreOptions = null;

    this.Edit = function (data) {
        var idcell = data.CellID;
        $('#' + idcell).focus();
        $('.anchor .moreoptions').css("display", "none");

    }

    this.Cancel = function (data) {
        var _arrayId = data.CellID.split('-');
        var _row = _arrayId[1];
        var _cell = _arrayId[0];
        var _ArrayErrorRows = ReviewImportModel.ErrorRows();
        var _ArrayValidation = ReviewImportModel.ColumnHeaders()[_cell].RegularExpressions;
        var _IsRequired = ReviewImportModel.ColumnHeaders()[_cell].IsRequired;
        var _check = false;
        if (_IsRequired) {
            _check = false;
        }
        else {
            _check = true;
        }

        if (_check) {
            if (_IsRequired) {
                _ArrayErrorRows[_row].Cells[_cell].Value = "";
                _ArrayErrorRows[_row].Cells[_cell].IsDone = false;
                _ArrayErrorRows[_row].Cells[_cell].IsError = true;
                _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";
                ReviewImportModel.ErrorRows([]);
                ReviewImportModel.ErrorRows(_ArrayErrorRows);
            }
            else {
                _ArrayErrorRows[_row].Cells[_cell].Value = "";
                _ArrayErrorRows[_row].Cells[_cell].IsDone = true;
                _ArrayErrorRows[_row].Cells[_cell].IsError = false;
                _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 done";
                //ReviewImportModel.ErrorRows([]);
                ReviewImportModel.ErrorRows(_ArrayErrorRows);
            }
        }
        else {
            _ArrayErrorRows[_row].Cells[_cell].Value = "";
            _ArrayErrorRows[_row].Cells[_cell].IsDone = false;
            _ArrayErrorRows[_row].Cells[_cell].IsError = true;
            _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";
            //ReviewImportModel.ErrorRows([]);
            ReviewImportModel.ErrorRows(_ArrayErrorRows);
        }
        var cellid = data.CellID;
        $('#' + cellid).focus();

        $('.anchor .moreoptions').css("display", "none");

        var scrollleft = $("#gridview").scrollLeft();

        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");
        }
    }

    this.EditDone = function (data) {
        if (data.ClassName == "col1 done") {
            var _value = data.Value;
            var _arrayId = data.CellID.split('-');
            var _row = _arrayId[1];
            var _cell = _arrayId[0];
            var _ArrayErrorRows = ReviewImportModel.ErrorRows();
            _ArrayErrorRows[_row].Cells[_cell].Value = "";
            //ReviewImportModel.ErrorRows([]);
            ReviewImportModel.ErrorRows(_ArrayErrorRows);
            ReviewImportModel.ErrorRows()[_row].Cells[_cell].Value = _value;
            var cellid = data.CellID;
            $('#' + cellid).focus();
            $('.anchor .moreoptions').css("display", "none");

            var idcell = data.CellID;
            $('#' + idcell + '-A').val(_value);
        }
        var scrollleft = $("#gridview").scrollLeft();

        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");
        }


    }

    this.BlurCell = function (data) {
        Update_Cell(data.Value, data.CellID);
    }

    this.ClickCell = function (data) {
        if (ReviewImportModel.ActiveMoreOptions != null)
            ReviewImportModel.ActiveMoreOptions.css("display", "none");
    }

    this.CheckColumnHeaders = ko.computed(function () {
        var countColumnHeaders = this.ColumnHeaders().length;
        var computedDisplayColumns = clone(this.ColumnHeaders());
        var computedDisplayErrorRows = clone(this.ErrorRows());
        var countErrorRows = this.ErrorRows().length;
        this.DisplayErrorRows([]);
        for (var i = countColumnHeaders - 1; i > -1; i--) {
            var columnHeader = this.ColumnHeaders()[i];
            if (columnHeader.IsIgnored == true) {
                computedDisplayColumns.splice(i, 1);
                for (var j = 0; j < countErrorRows; j++) {
                    var row = computedDisplayErrorRows[j];
                    row.Cells.splice(i, 1);
                }
            }
        }
        this.DisplayColumnHeaders(computedDisplayColumns);
        this.DisplayErrorRows(computedDisplayErrorRows);

    }, this);


    //Count blank
    this.CountBlank = ko.computed(function () {
        var intBlank = 0;
        var intError = 0;
        var countErrorRows = this.ErrorRows().length;
        if (countErrorRows > 0) {
            for (var i = 0; i < countErrorRows; i++) {
                if (!this.ErrorRows()[i].IgnoreWhenImport) {
                    for (var j = 0; j < this.ErrorRows()[i].Cells.length; j++) {
                        if (!this.ErrorRows()[i].Cells[j].IsIgnored) {
                            if (this.ErrorRows()[i].Cells[j].Value == "") {
                                intBlank = intBlank + 1;
                            }
                        }
                    }
                }
            }
        }
        return intBlank;
    }, this);


    // Count Errors
    this.CountError = ko.computed(function () {
        var intError = 0;
        var countErrorRows = this.ErrorRows().length;
        if (countErrorRows > 0) {
            for (var i = 0; i < countErrorRows; i++) {
                if (!this.ErrorRows()[i].IgnoreWhenImport) {
                    for (var j = 0; j < this.ErrorRows()[i].Cells.length; j++) {
                        if (!this.ErrorRows()[i].Cells[j].IsIgnored) {
                            if (this.ErrorRows()[i].Cells[j].IsError == true) {
                                intError = intError + 1;
                            }
                        }
                    }
                }
            }
        }
        if (intError == 0)
        { intError == "no"; }
        return intError;
    }, this);

    this.CountErrorG2 = ko.computed(function () {
        var intError = 0;
        var countErrorRows = this.ErrorRows().length;
        if (countErrorRows > 0) {
            for (var i = 0; i < countErrorRows; i++) {
                if (!this.ErrorRows()[i].IgnoreWhenImport) {
                    if (this.ErrorRows()[i].Cells.length > 2) {
                        for (var j = 2; j < this.ErrorRows()[i].Cells.length; j++) {
                            if (!this.ErrorRows()[i].Cells[j].IsIgnored) {
                                if (this.ErrorRows()[i].Cells[j].IsError == true) {
                                    intError = intError + 1;
                                }
                            }
                        }
                    }
                }
            }
        }
        return intError;
    }, this);

    //Set text for error
    this.txtCountError = ko.computed(function () {
        if (this.CountError() > 1) {

            if (this.CountBlank() == 0) {
                return "There are " + this.CountError() + " errors" + " and no blank fields in your file.";
            } if (this.CountBlank() == 1) {
                return "There are " + this.CountError() + " errors" + " and" + " blank field in your file.";
            }
            else {
                return "There are " + this.CountError() + " errors" + " and " +this.CountBlank()+ " blank fields in your file.";
            }

        }
        else if (this.CountError() == 1) 
        {
            if (this.CountBlank() == 0) 
            {
                return "There is " + this.CountError() + " error" + " and no blank fields in your file.";
            } if (this.CountBlank() == 1) {
                return "There is " + this.CountError() + " error " + " and " + this.CountBlank() + " blank field in your file.";
            }
            else 
            {
                return "There is " + this.CountError() + " error" + " and " + this.CountBlank() + " blank fields in your file.";
            }
        }
        else 
        {

            if (this.CountBlank() == 0)
             {
                 return "There are no errors " + "or missing data in your file.";
            } if (this.CountBlank() == 1) {
                return "There are no errors " + "and " + this.CountBlank() + " blank field in your file.";
            }
            else {
                return "There are no errors " + "and " + this.CountBlank() + " blank fields in your file.";
            }
        }

    }, this);
    //Set text for blank fields
    this.txtCountBlank = ko.computed(function () {
        if (this.CountBlank() != 1) {
            return "and blank fields";
        }
        else {
            return "or blank field";
        }

    }, this);

    //Set width for grid
    this.WidthGrid = ko.computed(function () {

        var _widthScroll = $('#gridview').width();
        var _heightScroll = $('#gridview').height();
        var _heightCell = 31;
        var _height = 32;
        var _width = 80;
        var _widthCell = 140;
        var countErrorRows = this.ErrorRows().length;
        var countColumnHeaders = this.ColumnHeaders().length;
        var HeaderNonXOut = this.ColumnHeaders().length;



        if (countColumnHeaders > 0) {
            for (var i = 0; i < countColumnHeaders; i++) {
                if (!this.ColumnHeaders()[i].IsIgnored) {
                    _width = _width + _widthCell;
                }

            }
        }

        if (countColumnHeaders > 0) {
            for (var i = 0; i < countColumnHeaders; i++) {
                if (this.ColumnHeaders()[i].IsIgnored) {
                    HeaderNonXOut = HeaderNonXOut - 1;
                }

            }
        }

        if (countErrorRows > 0) 
        {
            for (var i = 0; i < countErrorRows; i++) {
                if (!this.ErrorRows()[i].IgnoreWhenImport) {
                    _height = _height + _heightCell;
                }
            }
        }


        // scroll more errors

        var limit_number_column = parseInt(_widthScroll / 140);
        _width = _width - 343 + HeaderNonXOut;
        if (countErrorRows < 8 || (HeaderNonXOut - 2) <= limit_number_column) {

            $('#scrollbar').css("display", "none");

        }
        else {
            // Show errors count
            if (ReviewImportModel.CountErrorG2() > 0) {
                $('#scrollbar').css("display", "block");
            }
            else {
                $('#scrollbar').css("display", "none");
            }
        }

        return _width.toString() + "px";
    }, this);

    //Check last rows display
    this.LastRowDisplay = ko.computed(function () {
        var _LastRowDisplay = -1;
        var countErrorRows = this.ErrorRows().length;
        if (countErrorRows > 0) {
            for (var i = countErrorRows - 1; i >= 0; i--) {
                if (!this.ErrorRows()[i].IgnoreWhenImport) {
                    _LastRowDisplay = this.ErrorRows()[i].RowNumber;
                    break;
                }
            }
        }
        return _LastRowDisplay;
    }, this);

    this.ShowSuggestionmsg = ko.computed(function () {
        if (this.HasErrorsToDisplay()) {
            return true;
        }
        else {
            return false;
        }

    }, this);

    this.ShowDeleteBtn = ko.computed(function () {
        if (this.HasErrorsToDisplay()) {
            return true;
        }
        else {
            return false;
        }

    }, this);

    //Check show error msg
    this.titleReviewandImport = ko.computed(function () {


        if (this.HasErrorsToDisplay()) {
            return "We have identified some errors and missing data in your file."

        }
        else {
            if (this.DisplayErrorRows().length >= 5) {
                return "Below is an abbreviated listing of the first 5 leads for you to review.";

            }
            else {
                if (this.DisplayErrorRows().length != 1)
                    return "Below is a listing of " + this.DisplayErrorRows().length + " leads for you to review.";
                else
                    return "Below is a listing of " + this.DisplayErrorRows().length + " lead for you to review.";

            }
        }


    }, this);



    //Delete row
    this.x_OutRow = function (data) {
        var _ArrayError = ko.utils.arrayFilter(ReviewImportModel.ErrorRows(), function (RowError) {
            if (RowError.RowNumber == data.RowNumber) {
                RowError.IgnoreWhenImport = true;
            }
            return true;
        });
        ReviewImportModel.ErrorRows(_ArrayError);
    };

    //Check show button next
    this.DoNotImportLeadswithErrors = ko.observable(false);
    this.attrNextButton = ko.observable("btn btn-importleads-gray right");
    this.enableNextButton = ko.computed(function () {
        if (this.DoNotImportLeadswithErrors()) {
            this.attrNextButton("btn btn-importleads-blue right");
            return true;
        }
        else {
            if (this.CountError() == 0) {
                this.attrNextButton("btn btn-importleads-blue right");
                return true;
            }
            else {
                this.attrNextButton("btn btn-importleads-gray right");
                return false;
            }
        }
    }, this);

    //Send data to server
    this.SendDataToServer = function () {
        if (this.enableNextButton()) {

            init_send_data_to_server();

            var ManualImportId = $('#StoreManualID').val();
            var session = $('#StoreSession').val();
            var DoNotImportLeadswithErrors = this.DoNotImportLeadswithErrors();
            var hasError = false;
            if (this.HasErrorsToDisplay() == true) {
                for (var i = 0; i < this.ErrorRows().length; i++) {
                    var rowData = { session: session, errorRow: this.ErrorRows()[i] };
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: "/EnhancedManualImport/SendRowToServer",
                        contentType: "application/json; charset=utf-8",
                        dataType: "JSON",
                        data: JSON.stringify(rowData),
                        success: function (datareturn) {
                            if (datareturn != '') {
                                $.fancybox.close();
                                showCustomError(datareturn);
                                hasError = true;
                            }
                        },
                        error: function (xhr, status, error) {
                            // Boil the ASP.NET AJAX error down to JSON.
                            var err = eval("(" + xhr.responseText + ")");

                            // Display the specific error raised by the server (e.g. not a
                            //   valid value for Int32, or attempted to divide by zero).
                            $.fancybox.close();
                            showCustomError(err);
                            hasError = true;
                        }
                    });
                    if (hasError == true) {
                        break;
                    }
                }
            }
            if (hasError == false) {
                var data = {
                    session: session,
                    manualImportID: ManualImportId,
                    DoNotImportLeadswithErrors: DoNotImportLeadswithErrors
                };
                $.ajax({
                    async: false,
                    type: "POST",
                    url: "/EnhancedManualImport/CommitSendDataToServer",
                    contentType: "application/json; charset=utf-8",
                    dataType: "JSON",
                    data: JSON.stringify(data),
                    success: function (datareturn) {
                        if (datareturn == '') {
                            //$.fancybox.close();
                            var link = "/Lead/";
                            window.location = link;
                        }
                        else {
                            $.fancybox.close();
                            showCustomError(datareturn);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Boil the ASP.NET AJAX error down to JSON.
                        var err = eval("(" + xhr.responseText + ")");
                        $.fancybox.close();
                        // Display the specific error raised by the server (e.g. not a
                        //   valid value for Int32, or attempted to divide by zero).
                        showCustomError(err);

                    }
                });
            }
        }
    }

    this.GoBackToStepTwo = function () {
        UploadFileModel.DisplayFirstView(false);
        HelpModel.DisplayHelp(false);
        MappingModel.DisplaySecondView(true);
        ReviewImportModel.DisplayThirdView(false);
        
    }
};



/*to use for dragging and dropping*/
ko.bindingHandlers.itemDrag =
{
    init: function (element) {
        $(element).draggable({
            revert: "invalid",
            containment: '#wrapper',
            appendTo: 'body',
            helper: 'clone'
        });
    }
}

ko.bindingHandlers.itemDrop =
{
    init: function (element) {
        $(element).droppable({
            accept: ".i-matched1",
            drop: function (event, ui) {
                var DragDataId = ui.draggable.find(".IdField").val();
                var DragFieldName = ui.draggable.find(".FieldName").text();
                MappingModel.MatchColumn(DragDataId, DragFieldName);
                MappingModel.SearchFieldText("Search Header Names");
                MappingModel.UpdateView();
                ui.draggable.remove();
                $('.match-header').css("overflow", "auto");
                $('.panel').css("overflow", "auto");
                if (($("#searchKeywordstep2").is(":focus")) && ($('#searchKeywordstep2').val() == "Search Header Names")) {
                    $('#searchKeywordstep2').val("");
                }
            }
        });
    }
}

ko.bindingHandlers.itemDropBack =
{
    init: function (element) {
        $(element).droppable({
            accept: ".i-matched",
            drop: function (event, ui) {
                var HeaderName = ui.draggable.parent().find(".lb").text();
                MappingModel.UnMatchColumn(HeaderName, false);
                MappingModel.SearchFieldText("Search Header Names");
                MappingModel.UpdateView();
                ui.draggable.remove();
                $('.match-header').css("overflow", "auto");
                $('.panel').css("overflow", "auto");
                if (($("#searchKeywordstep2").is(":focus")) && ($('#searchKeywordstep2').val() == "Search Header Names")) {
                    $('#searchKeywordstep2').val("");
                }
            }
        });
    }
}
ko.bindingHandlers.itemDragBack =
{
    init: function (element) {
        $(element).draggable({
            revert: 'invalid',
            containment: '#wrapper',
            start: function () {
                $('#matchrightside').css("z-index", "1000");
                $('.match-header').css("overflow", "visible");
                $('.panel').css("overflow", "visible");
                $('#matchrightside .i-matched').css("z-index", "100");
                $('#matchrightside .i-matched1').css("z-index", "100");
            },
            appendTo: '#matchrightside',
            helper: 'clone'
        });
    }
}

ko.bindingHandlers.griddropdown =
{
    init: function (element) 
    {

        $(element).click(function () {
            if (ReviewImportModel.ActiveMoreOptions != null)
                ReviewImportModel.ActiveMoreOptions.css("display", "none");
            ReviewImportModel.ActiveMoreOptions = $(element).parent().find('.moreoptions');

            ReviewImportModel.ActiveMoreOptions.css("display", "block");

            showtoltip();

        });
   }
}

ko.applyBindings(UploadFileModel, document.getElementById("ImportLeadFirstStep"));
ko.applyBindings(HelpModel, document.getElementById("ImportLeadHelp"));
ko.applyBindings(MappingModel, document.getElementById("ImportLeadSecondStep"));
ko.applyBindings(ReviewImportModel, document.getElementById("ImportLeadThirdStep"));

/*----------------------------------------------------------------
FUNCTIONS---------------------------------------------/*
/*to post the seleted file*/

function ContinueClick() {
    init_mapping();
    document.getElementById("UploadFile").click();
}

function init_review_import() {
    $.fancybox($('#popup-processing-reviewimport'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.8,
                css: { 'background-color': '#11619d' },
                closeClick: false
            }
        }
    });
}

function ChangeViewType(vt) {
    MappingModel.ViewType = vt;
    if (MappingModel.Initialized) {
        MappingModel.UpdateView();
    }
}

//Edit cell
function Keypress_Event(evt, value, id) {
    var charCode = (evt.which) ? evt.which : evt.keyCode

    if (charCode == 13 || charCode == 9) {
        Update_Cell(value, id);

        var scrollleft = $("#gridview").scrollLeft();
       

        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");
        }
    }

    return true;
}
//Validation cell
function Update_Cell(value, id) {
    var _arrayId = id.split('-');
    var _row = _arrayId[1];
    var _cell = _arrayId[0];
    var _ArrayErrorRows = ReviewImportModel.ErrorRows();
    var _ArrayValidation = ReviewImportModel.ColumnHeaders()[_cell].RegularExpressions;
    _ArrayValidation = _ArrayValidation.replace(/\/g, "\\");
    console.log(_ArrayValidation);
    var _IsRequired = ReviewImportModel.ColumnHeaders()[_cell].IsRequired;
    var _check = false;



    if (_IsRequired) {
        if (value != "") {
            if (_ArrayValidation.length > 0) {
                for (var i = 0; i < _ArrayValidation.length; i++) {
                    if (CheckValidation(value, _ArrayValidation[i])) {
                        _check = true;
                        break;
                    }
                }
            }
            else {
                _check = true;
            }
        }
        else {
            _check = false;
        }
    }
    else {
        if (value != "") {
            if (_ArrayValidation.length > 0) {
                for (var i = 0; i < _ArrayValidation.length; i++) {
                    if (CheckValidation(value, _ArrayValidation[i])) {
                        _check = true;
                        break;
                    }
                }
            }
            else {
                _check = true;
            }
        }
        else {
            _check = true;
        }
    }
    //validating for Firstname and Lastname
    if (ReviewImportModel.ColumnHeaders()[_cell].RegularExpressions.length == 0) {
        if (value != undefined && value != null) {
            for (var i = 0; i < value.length; i++) {
                if (value[i] == "<" || value[i] == ">") {
                    _check = false;
                    break;
                }
            }
        }
    }

    if (_check) {
        _ArrayErrorRows[_row].Cells[_cell].Value = value;
        _ArrayErrorRows[_row].Cells[_cell].IsDone = true;
        _ArrayErrorRows[_row].Cells[_cell].IsError = false;
        _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 done";
        //ReviewImportModel.ErrorRows([]);
        ReviewImportModel.ErrorRows(_ArrayErrorRows);
    }
    else {
        _ArrayErrorRows[_row].Cells[_cell].Value = value;
        _ArrayErrorRows[_row].Cells[_cell].IsDone = false;
        _ArrayErrorRows[_row].Cells[_cell].IsError = true;
        _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";

        //ReviewImportModel.ErrorRows([]);
        ReviewImportModel.ErrorRows(_ArrayErrorRows);
    }


}

function showtoltip() {
    $('#gridview').scroll(function () {
        var scrollleft = $("#gridview").scrollLeft();
       

        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");

        }
        else
            if (ReviewImportModel.CountErrorG2() > 0) {
                $('#scrollbar').css("display", "block");
            }
    });
}

//Check validation
function CheckValidation(value, pattern) {
    var regExp = new RegExp(pattern, "");
    return regExp.test(value);
}
function init_send_data_to_server() {
    $.fancybox($('#popup-processing-senddata'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay:
			{
			    opacity: 0.8,
			    css: { 'background-color': '#11619d' },
			    closeClick: false
			}
        }
    });
}
function updateLeadStatus() {
    var strLeadStatus = !UploadFileModel.classLead();
    var data = { "LeadStatus": strLeadStatus };
    $.post("/LeadCall/UpdateLeadStatus", data, function (LeadStatus) {
        UploadFileModel.classLead(LeadStatus);
        HelpModel.classLead(LeadStatus);
        MappingModel.classLead(LeadStatus);
        ReviewImportModel.classLead(LeadStatus);
    });

}
function updateCallStatus()
 {
    var strCallStatus = !UploadFileModel.classCall();
    var data = { "CallStatus": strCallStatus };
    $.post("/LeadCall/UpdateCallStatus", data, function (CallStatus) {
        UploadFileModel.classCall(CallStatus);
        HelpModel.classCall(CallStatus);
        MappingModel.classCall(CallStatus);
        ReviewImportModel.classCall(CallStatus);
    });
}


function hscroll_size() 
{
    setTimeout(function ()
    {
        var tblWidth = $("#gridview > div.title div.col1").length * 141+3;
        $("#gridview > div > div.line, #gridview > div:has(div.line)").css("minWidth", tblWidth);

        $("div#gridview, div#gridview > div.title, div#gridview > div > div.line").width("");

        var newWidth = $("div#panelReview").width() - 351;
        $("div#gridview").width(newWidth);
    }, 0);
}

//to set width for grid and handle for scrolling
$(document).ready(function () {
    var widthfull = $('#panelReview').width();
    $('#gridview').width("");
    $('#gridview').css("width", widthfull - 385);

    var currentSearchText = $('#searchKeywordstep2').val();
    var textDefault = "Search Header Names";
    $('#searchKeywordstep2').focus(function () {
        currentSearchText = $('#searchKeywordstep2').val();
        if ($(this).val() == textDefault) {
            $(this).val("");
        }
    });

    $('#searchKeywordstep2').blur(function () {
        if ((($(this).val() == null) || ($(this).val() == '')) && (currentSearchText == textDefault)) {
            $(this).val(textDefault);
        }
    });

    $('#gridview').scroll(function () {

        var scrollleft = $("#gridview").scrollLeft();


        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");

        }
        else if (ReviewImportModel.CountErrorG2() > 0) {
            $('#scrollbar').css("display", "block");
        }

    });

});

$(window).resize(function ()
 {
    hscroll_size();
});
